package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.DrawActivityRepository;
import cn.com.connext.scrm.repository.master.DrawPrizeCountRepository;
import cn.com.connext.scrm.repository.master.PrizeExtRepository;
import cn.com.connext.scrm.repository.master.ZnhjRepository;
import cn.com.connext.scrm.service.*;
import cn.com.connext.scrm.service.dto.DrawActivityDTO;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.PrizeDTO;
import cn.com.connext.scrm.service.mapper.ClickCountService;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.service.mapper.PrizeMapper;
import cn.com.connext.scrm.utils.CouponUtils;
import cn.com.connext.scrm.web.rest.resp.CouponQueryResp;
import cn.com.connext.scrm.web.rest.vm.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.connext.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.ListUtils;

import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 2 * @Author: shawn
 * 3 * @Date: 2020/8/11 4:05 下午
 * 4
 */
@RestController
@RequestMapping("/api/prize/")
public class PrizeResource {

    private final Logger log = LoggerFactory.getLogger(PrizeResource.class);

    @Autowired
    private PrizeGoodService prizeGoodService;

    @Autowired
    private PrizeService prizeService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private PrizeExtRepository prizeExtRepository;

    private Lock lock = new ReentrantLock();

    @Value("${prize.needPoint}")
    private Integer needPoint;

    @Autowired
    private ActivityService activityService;
    @Autowired
    private DwaGetCouponService dwaGetCouponService;

    @Autowired
    private ClickCountService clickCountService;

    @Autowired
    CodeUserService codeUserService;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    @Autowired
    private DrawPrizeCountRepository drawPrizeCountRepository;

    @Autowired
    private ZnhjRepository znhjRepository;
    /**
     * 编辑奖品
     *
     * @param vm
     * @return
     */
    @PostMapping("edit")
    public JsonResult edit(@RequestBody PrizeGoodVM vm) {
        JsonResult result = new JsonResult();
        try {
            //实物需要检验code
            if (1==vm.getType()) {
                /* 20210420新加礼品CODE校验*/
                if(StringUtils.isBlank(vm.getGoodCode())) {
                    result.setMessage("奖品CODE不能为空");
                    result.setState(-1);
                    return result;
                }
                // 判断ID为空 是新增奖品
                if (ObjectUtils.isEmpty(vm.getId())) {
                    List<PrizeGood> prizeGoodList = prizeGoodService.findByGoodCode(vm.getGoodCode());
                    if (!ListUtils.isEmpty(prizeGoodList)) {
                        result.setMessage("奖品CODE已存在");
                        result.setState(-1);
                        return result;
                    }
                } else {// ID不为空编辑奖品
                    List<PrizeGood> prizeGoodList = prizeGoodService.findByGoodCodeAndId(vm.getGoodCode(), vm.getId());
                    if (!ListUtils.isEmpty(prizeGoodList)) {
                        result.setMessage("奖品CODE已存在");
                        result.setState(-1);
                        return result;
                    }
                }  /* 20210420新加礼品CODE校验结束*/
            }


            prizeGoodService.edit(vm);
            result.setState(0);
            result.setMessage("成功");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setMessage("系统繁忙");
            result.setState(-1);
        }
        return result;
    }

    @PostMapping("list")
    public JsonResult list(@RequestBody QueryPrizeVM vm) {
        JsonResult result = new JsonResult();
        Page<PrizeGood> list = prizeGoodService.list(vm);
        result.setData(list);
        result.setState(0);
        return result;
    }

    @PostMapping("detail")
    public JsonResult detail(@RequestBody IdVM vm) {
        JsonResult result = new JsonResult();
        try {
            PrizeGood good = prizeGoodService.detail(vm.getId());
            result.setState(0);
            result.setData(good);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }
        return result;
    }

    @PostMapping("deletePrizeGood")
    public JsonResult delete(@RequestBody IdVM vm) {
        JsonResult result = new JsonResult();
        try {
            prizeGoodService.delete(vm.getId());
            result.setState(0);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }
        return result;
    }

    @PostMapping("enable")
    public JsonResult enable(@RequestBody IdVM vm) {
        JsonResult result = new JsonResult();
        try {
            prizeGoodService.enable(vm.getId());
            result.setState(0);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }
        return result;
    }

//    /*
//    仅仅为泰斯卡抽奖活动
//     */
//    @PostMapping("prize")
//    public JsonResult prize(@RequestBody PrizeVM vm) {
//        String avtivityId = "TaliskerPrizeActivity";
//        JsonResult result = new JsonResult();
//        if (StringUtils.isEmpty(vm.getUnionId())) {
//            result.setState(-1);
//            result.setMessage("unionId为空");
//            return result;
//        }
//        try {
//            Prize prize = prizeService.findByUnionId(vm.getUnionId());
//            if (prize != null) {
//                PrizeDTO dto = prizeMapper.toDto(prize);
//                PrizeExt ext = prizeExtRepository.findByPrizeId(prize.getId());
//                if (ext != null) {
//                    dto.setPrizeExt(ext);
//                } else {
//                    dto.setPrizeExt(new PrizeExt());
//                }
//                PrizeGood good = prizeGoodService.findById(prize.getGoodId());
//                if (good != null) {
//                    dto.setGoodName(good.getGoodName());
//                    dto.setType(good.getType());
//                }
//                result.setData(dto);
//                result.setState(-1);
//                result.setMessage("已经抽过奖了");
//                return result;
//            }
//            String memberShipId = memberService.findMemberShipIdByUnionId(vm.getUnionId());
//            if (StringUtils.isEmpty(memberShipId)) {
//                result.setMessage("请先注册为CRM会员");
//                result.setState(-1);
//                return result;
//            }
//            ResponseEntity<JSONObject> memberInfo = memberService.findOneDTO(memberShipId);
//            Integer point = (Integer) memberInfo.getBody().get("point");
//            log.info("point:{}", point);
//            if (point < needPoint) {
//                result.setMessage("当前积分小于" + needPoint + "分,无法抽奖");
//                result.setState(-1);
//                return result;
//            }
//            result = prizeService.prize(vm.getUnionId(), memberShipId, "", 1);
//        } catch (Exception e) {
//            log.error("e:{}", e);
//            result.setState(-1);
//            result.setMessage("系统繁忙");
//        }
//        return result;
//    }

    /*
    仅仅为泰斯卡抽奖活动
     */
    @PostMapping("prize")
    public JsonResult prize(@RequestBody PrizeVM vm) {
        String activityId = "TaliskerPrizeActivity";

        NewPrizeVM vm2 = new NewPrizeVM();
        vm2.setUnionId(vm.getUnionId());
        vm2.setActivityId(activityId);

        return newPrize(vm2);
    }

    /**
     * 抽奖接口
     *
     * @param vm
     * @return
     */
    @PostMapping("/new/prize")
    public JsonResult newPrize(@RequestBody NewPrizeVM vm) {
        log.info("获取当前入参：{},{}", vm.getActivityId(), vm.getUnionId());
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(vm.getUnionId())) {
            result.setState(-1);
            result.setMessage("unionId为空");
            return result;
        }
        lock.lock();
        try {
            if ("JohnnieWalkerSubmissionCode".equals(vm.getActivityId())) {
                if (StringUtils.isBlank(vm.getBottleUnique())) {
                    result.setState(-1);
                    result.setMessage("瓶码唯一码为空");
                    return result;
                }
                //尊尼一物一码校验
                ZnhjEntity znhjEntity = znhjRepository.finByBottomUniqueCode(vm.getBottleUnique());
                if (null == znhjEntity) {
                    result.setState(-1);
                    result.setMessage("无效的瓶码唯一码");
                    return result;
                }
                if (StringUtils.isNotBlank(znhjEntity.getIsPrize())&&"1".equals(znhjEntity.getIsPrize())) {
                    result.setState(-1);
                    result.setMessage("瓶码唯一码已被使用");
                    return result;
                } else {
                    // 更改瓶码数据
                    znhjRepository.updateByBottomUniqueCode(vm.getBottleUnique());
                }
            }

            DrawActivityDTO activityDTO = activityService.drawDetail(vm.getActivityId());
            if("smpBaileysFlActivity".equals(vm.getActivityId())){
                //判断是否有抽奖纪录
                List<Prize> prizes = prizeService.findByUnionIdAndActivityId(vm.getUnionId(), vm.getActivityId());
                if (prizes.size() >= activityDTO.getJoinNumber()) {
                    // -2 表示参与次数以上限
                    result.setState(-2);
                    result.setMessage("参与次数已到上限");
                    return result;
                }
                String memberShipId = memberService.findMemberShipIdByUnionId(vm.getUnionId());
                if (StringUtils.isEmpty(memberShipId)) {
                    result.setMessage("请先注册为CRM会员");
                    result.setState(-1);
                    return result;
                }
                //获取用当前积分
                ResponseEntity<JSONObject> memberInfo = memberService.findOneDTO(memberShipId);
                Integer point = (Integer) memberInfo.getBody().get("point")==null?0:(Integer) memberInfo.getBody().get("point");
                log.info("point:{}", point);
                if (point < activityDTO.getNeedPoint()) {
                    result.setMessage("当前积分小于" + activityDTO.getNeedPoint() + "分,无法参与活动");
                    result.setState(-1);
                    return result;
                }
                List<CodeUser> codeUser = codeUserService.findByUnionIdAndCodeId(vm.getUnionId(),vm.getCodeId());
                if (codeUser.size()>=1){
                    result.setState(-1);
                    result.setMessage("您已经扫过此码了");
                    return result;
                }
                List<CodeUser> byCodeId = codeUserService.findByCodeId(vm.getCodeId());
                if (byCodeId.size()>=3){
                    result.setState(-1);
                    result.setMessage("此码参与次数已达三次");
                    return result;
                }
                DateFormat dateInstance = DateFormat.getDateInstance();
                String date = dateInstance.format(new Date());
                Date createtime = dateInstance.parse(date);
                List<CodeUser> byUnionId= codeUserService.findByUnionIdAndCreatetimeLike(vm.getUnionId(),createtime);
                if (byUnionId.size()>=5){
                    result.setState(-1);
                    result.setMessage("您今天参与次数已达5次");
                    return result;
                }
               // List<PrizeGood> pggoodlist = prizeGoodService.getEnableIdsAndStockIsNotNullByActivityId(vm.getActivityId());
                List<PrizeGood> pglist = null;
                List<Prize> prizeList = prizeService.findUnionId(vm.getUnionId());
                Integer pgcount=0;
                if(prizeList !=null && prizeList.size() >0 &&pgcount<10){
                    for(int i =0;i<prizeList.size();i++){
                        PrizeGood pg = prizeGoodService.findById(prizeList.get(i).getGoodId());
                        if(pg !=null) {
                            int isbig = pg.getIsbig() == null ? 0 : pg.getIsbig();
                            if (isbig == 1) {
                                pgcount++;
                                List<Prize> prizecount = prizeService.findByUnionIdAndGoodId(vm.getUnionId(), pg.getGoodId());
                                List<Integer> goodIdList = new ArrayList<>();
                                if (prizecount != null && prizecount.size() >= pg.getBigcount()) {
                                    pglist = new ArrayList<>();
                                    if (!goodIdList.contains(pg.getGoodId())) {
                                        pglist.add(pg);
                                        goodIdList.add(pg.getGoodId());
                                        break;
                                    }

                                }
//                            pglist = prizeGoodService.findByActivityId(pg.getActivityId());
                            }
                        }
                    }
                }
                /*if (pglist != null && pglist.size()>0){
                    HashSet list1 = new HashSet(pggoodlist);
                    HashSet list2 = new HashSet(pglist);
                    list1.removeAll(list2);
                    pggoodlist.removeAll(pglist);
                    pggoodlist.clear();
                    pggoodlist.addAll(list1);
                }*/
                result = prizeService.prizeLLs(vm.getUnionId(),pglist,memberShipId, vm.getActivityId(), activityDTO.getNeedPoint(),vm);
            }else {
                DrawActivity activity = drawActivityRepository.findOne(vm.getActivityId());
                //判断活动类型为抽奖并且包含未中奖
                if (StringUtils.equals(activity.getActivityType(), "1") && activity.getNotHavePrizeFlag() == 1) {
                    DrawPrizeCount drawPrizeCount = drawPrizeCountRepository.queryDrawPrizeCountByActivityId(activity.getId(),vm.getUnionId());
                    if (drawPrizeCount != null &&  drawPrizeCount.getPrizeNum() >= activityDTO.getJoinNumber()) {
                        // -2 表示参与次数以上限
                        result.setState(-2);
                        result.setMessage("参与次数已到上限");
                        return result;
                    }
                } else {
                    //判断是否有抽奖纪录
                    List<Prize> prizes = prizeService.findByUnionIdAndActivityId(vm.getUnionId(), vm.getActivityId());
                    if (prizes.size() >= activityDTO.getJoinNumber()) {
                        // -2 表示参与次数以上限
                        result.setState(-2);
                        result.setMessage("参与次数已到上限");
                        return result;
                    }
                }
                String memberShipId = memberService.findMemberShipIdByUnionId(vm.getUnionId());
                if (StringUtils.isEmpty(memberShipId)) {
                    result.setMessage("请先注册为CRM会员");
                    result.setState(-1);
                    return result;
                }
                //获取用当前积分
                ResponseEntity<JSONObject> memberInfo = memberService.findOneDTO(memberShipId);
                Integer point = (Integer) memberInfo.getBody().get("point")==null ?0:(Integer) memberInfo.getBody().get("point");
                log.info("point:{}", point);
                int activityPoint =activityDTO.getNeedPoint() == null?0:activityDTO.getNeedPoint();
                if (point < activityPoint) {
                    result.setMessage("当前积分小于" + activityPoint + "分,无法参与活动");
                    result.setState(-1);
                    return result;
                }
                result = prizeService.prize(vm.getUnionId(), memberShipId, vm.getActivityId(), activityPoint,vm.getOpenId(),vm.getType(),vm.getIsReceive());
            }

        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }finally {
                lock.unlock();
        }
        return result;
    }


    /**
     * 分页获取中奖纪录
     *
     * @param vm
     * @return
     */
    @PostMapping("prizeList")
    public JsonResult prizeList(@RequestBody PrizeListVM vm) {
        JsonResult result = new JsonResult();
        try {
            Page<PrizeDTO> page = prizeService.prizeList(vm);
            result.setData(page);
            result.setState(0);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 中奖填写收货地址
     *
     * @param vm
     * @return
     */
    @PostMapping("editPrizeExt")
    public JsonResult editPrizeExt(@RequestBody PrizeExtVM vm) {
        JsonResult result = new JsonResult();
        try {
            if (vm.getPrizeId() == null) {
                result.setState(-1);
                result.setMessage("抽奖id为空");
                return result;
            }
            Integer goodId = prizeService.findGoodIdByPrizeId(vm.getPrizeId());
            PrizeGood prizeGood = prizeGoodService.findById(goodId);
            if (prizeGood == null) {
                if(prizeGood.getType() != 1 && !"SWQ".equals(prizeGood.getCouponType())){
                    result.setState(-1);
                    result.setMessage("只有抽中实物或者实物券的奖品才能填写收货地址");
                    return result;
                }
            }
            prizeService.createExt(vm);
            result.setState(0);
            result.setMessage("success");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setMessage("系统繁忙");
            result.setState(-1);
        }
        return result;
    }

    /**
     * 编辑中奖概率
     *
     * @param vm
     * @return
     */
    @PostMapping("editPrizeRate")
    public JsonResult editPrizeRate(@RequestBody PrizeRateVM vm) {
        JsonResult result = new JsonResult();
        try {
            if (vm.getGoodId() == null || 0 == vm.getGoodId()) {
                result.setState(-1);
                result.setMessage("概率id为空");
                return result;
            }
            if (vm.getNum() == null) {
                result.setState(-1);
                result.setMessage("概率范围值为空");
                return result;
            }
            prizeService.editRate(vm.getGoodId(), vm.getNum());
            result.setState(0);
            result.setMessage("success");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setMessage("系统繁忙");
            result.setState(-1);
        }
        return result;
    }

    /**
     * 奖品概率列表
     *
     * @param vm
     * @return
     */
    @PostMapping("rateList")
    public JsonResult rateList(@RequestBody PageQueryVM vm) {
        JsonResult result = new JsonResult();
        try {
            Page<PrizeRate> page = prizeService.rateList(vm.getPage(), vm.getPageSize());
            result.setData(page);
            result.setState(0);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 删除概率区间
     *
     * @param vm
     * @return
     */
    @PostMapping("deletePrizeRate")
    public JsonResult deletePrizeRate(@RequestBody IdVM vm) {
        JsonResult result = new JsonResult();
        try {
            prizeService.deleteRate(vm.getId());
            result.setState(0);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }
        return result;
    }


    /**
     * 查询当前用户中奖信息
     * @param vm
     * @return
     */
    @PostMapping("findPrizeByUnionId")
    public JsonResult findPrizeByMobile(@RequestBody PrizePageVM vm) {
        JsonResult result = new JsonResult();
        try {
            if(StringUtils.isEmpty(vm.getUnionId())){
                result.setState(-1);
                result.setMessage("缺少unionId参数");
            }else{
//                if(StringUtils.isEmpty(vm.getActivityId())){
                Page<PrizeDTO> page = prizeService.findPrizeByUnionId(vm);
                result.setData(page);
                result.setState(0);
//                }else{
//                    Page<PrizeCodeDTO> page = prizeService.findCodePrizeByUnionId(vm);
//                    result.setData(page);
//                    result.setState(0);
//                }
            }
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 查询当前用户中奖信息
     * @param vm
     * @return
     */
    @PostMapping("findCodeDetail")
    public JsonResult findCodeDetail(@RequestBody CodeVM vm) {
        JsonResult result = new JsonResult();
        try {
            if(vm.getPrizeId()==null){
                result.setState(-1);
                result.setMessage("缺少参数:prizeId");
            }else{
                PrizeCode code = prizeService.findPrizeCode(vm);
                result.setData(code);
                result.setState(0);
            }
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 判断用户是否领取过优惠券
     * @param vm
     * @return
     */
    @PostMapping("checkIsReceive")
    public JsonResult checkIsReceive(@RequestBody DwaIsReceiveVM vm) {
        JsonResult result = new JsonResult();
        try {
            List<DwaGetCoupon> list = dwaGetCouponService.checkIsReceive(vm);
            if(list !=null && list.size() >0){
                result.setState(0);
                result.setMessage("已领取过优惠券");
            }else{
                result.setState(1);
                result.setMessage("还未领取优惠券!,去领取");
            }
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 用户领取优惠券
     * @param vm
     * @return
     */
    @PostMapping("userGetCoupon")
    public JsonResult userGetCoupon(@RequestBody DwaIsReceiveVM vm) {
        log.info("isReceive:{}", vm.getIsReceive());
        JsonResult result = new JsonResult();
        try {
            List<PrizeGood> pglist = prizeGoodService.findByActivityId(vm.getActivityId());
            if(pglist.size()==0){
                result.setState(-1);
                result.setMessage("领取失败,该活动不存在优惠券！");
                return result;
            }
            List<DwaGetCoupon> dwaGetCoupon = dwaGetCouponService.checkIsReceive(vm);
            if(dwaGetCoupon !=null && dwaGetCoupon.size() >0){
                result.setState(0);
                result.setMessage("该用户已领取过优惠券，可直接使用");
            }else{
                result =dwaGetCouponService.addCoupon(pglist,vm);
            }
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("领取失败");
        }
        return result;
    }

    /**
     * 查询用户所有优惠券信息
     * @param vm
     * @return
     */
    @PostMapping("getAllCouponByUserMsg")
    public JsonResult getAllCouponByUserMsg(@RequestBody DwaIsReceiveVM vm) {
        JsonResult result = new JsonResult();
        try {
           //根据用户id查询活动信息
            List<DwaGetCoupon> list = dwaGetCouponService.findByActivityIdAndUnionId(vm.getActivityId(),vm.getUnionId());

            DwaConvertCode codeEntity = dwaGetCouponService.findTopCouponByUnionId(vm.getUnionId());
            CouponReturnVm cpvm = new CouponReturnVm();
            if(codeEntity !=null){
                cpvm.setTopCoupon(codeEntity);
            }

            Integer clickCount = getClickCount(vm.getActivityId(), vm.getUnionId());
            int count = clickCount == null ? 0 : clickCount;
            cpvm.setClickCount(count);
            //根据活动id查询券信息
            if(list!=null && list.size() >0){
                List<Integer> goodIds =new ArrayList<>();
                for (DwaGetCoupon dwa:list) {
                    goodIds.add(dwa.getGoodId());
                }
                List<PrizeGood> pglist = prizeGoodService.findDwaByActivityIdAndGoodIds(vm.getActivityId(),goodIds);
                List<PrizeGood> returnList =new ArrayList<>();
                PrizeGood prizeGood =null;
                if(pglist !=null && pglist.size() >0){
                    for (PrizeGood pg:pglist) {
                         Prize prize =prizeService.findByUnionIdAndActivityIdAndGoodId(vm.getUnionId(),vm.getActivityId(),pg.getId());
                         if(prize !=null){
                             prizeGood = new PrizeGood();
                             BeanUtils.copyProperties(pg, prizeGood);
                             prizeGood.setId(prize.getId());
                             prizeGood.setGoodId(pg.getId());
                             returnList.add(prizeGood);
                         }
                    }
                }
                if(returnList !=null && returnList.size() >0) {
                    Map<String, List<PrizeGood>> map = returnList.stream().collect(
                        Collectors.groupingBy(o -> CouponUtils.parse_yyyyMM(o.getStartTime()))
                    );
                    Map<String, List<PrizeGood>> listMap = CouponUtils.sortByKey(map);
                    cpvm.setBottomCoupon(listMap);
                }
            }
            //根据用户unionId查询top券信息
            result.setState(0);
            result.setData(cpvm);
            result.setMessage("数据如上");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 查询用户所有优惠券信息
     * @param vm
     * @return
     */
    @PostMapping("getExpiredCoupon")
    public JsonResult getExpiredCoupon(@RequestBody DwaIsReceiveVM vm) {
        JsonResult result = new JsonResult();
        try {
            //根据用户id查询活动信息
            List<DwaGetCoupon> dwlist = dwaGetCouponService.findByActivityIdAndUnionId(vm.getActivityId(),vm.getUnionId());
            CouponReturnVm cpvm = new CouponReturnVm();
            //根据活动id查询券信息
            if(dwlist!=null && dwlist.size() >0){
                List<Integer> goodIds =new ArrayList<>();
                for (DwaGetCoupon dwa:dwlist) {
                    goodIds.add(dwa.getGoodId());
                }
                List<PrizeGood> list = prizeGoodService.findExpiredDwaByActivityId(vm.getActivityId(),goodIds);
                Map<String, List<PrizeGood>> map = list.stream().collect(
                    Collectors.groupingBy(o -> CouponUtils.parse_yyyyMM(o.getEndTime()))
                );
                Map<String, List<PrizeGood>> listMap = CouponUtils.sortByKey(map);
                cpvm.setBottomCoupon(listMap);
            }
            Integer clickCount = getClickCount(vm.getActivityId(), vm.getUnionId());
            int count = clickCount == null ? 0 : clickCount;
            cpvm.setClickCount(count);
            //根据用户unionId查询top券信息
            result.setState(0);
            result.setData(cpvm);
            result.setMessage("数据如上");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 查看该活动改用户点击次数
     * @param
     * @return
     */
    public  Integer getClickCount(String activityId,String unionId) {
        JsonResult result = new JsonResult();
        int count = 0;
        try {
            //根据用户id查询活动信息
            ClickCount entity = clickCountService.findByActivityIdAndUnionId(activityId, unionId);
            if (entity != null) {
                count = entity.getCount();
            }
        }catch (Exception e){
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return count;
    }

    /**
     * 点击添加次数
     * @param vm
     * @return
     */
    @PostMapping("addClickCount")
    public JsonResult addClickCount(@RequestBody DwaIsReceiveVM vm) {
        JsonResult result = new JsonResult();
        //根据用户id查询活动信息
         try {
            clickCountService.addClickCount(vm.getActivityId(),vm.getUnionId());
            //根据用户unionId查询top券信息
            result.setState(0);
            result.setMessage("操作完成");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 定时任务清空次数
     * @param
     * @return
     */
    //每日最后一天
    @Scheduled(cron = "0 59 23 28-31 * ?")
    public JsonResult clearClickCount() {
        JsonResult result = new JsonResult();
        clickCountService.clearClickCount();
        result.setState(0);
        result.setMessage("定时任务操作完成");
        return result;
    }



    /**
     * 查询用户所有券信息
     * @param vm
     * @return
     */
    @PostMapping("getAllCouponByUserId")
    public JsonResult getAllCouponByUserId(@RequestBody DwaIsReceiveVM vm) {
        JsonResult result = new JsonResult();
        try {
            Map<String,Object> map = new HashMap<>();
            List<CouponQueryResp> allList = new ArrayList<>();
            List<Integer> typeList = new ArrayList<>();
            if(vm.getType() ==1){
                //查询所有组合卡券
                CouponReturnVm groupCoupon = prizeService.getCouponReturnVm(vm);
                map.put("groupCoupon",groupCoupon);
                //查询所有活动券
                List<OrderRecord> orderlist =orderService.findOrderByUserId(vm.getUnionId());
                typeList.add(1);
                List<Prize> prizeList =prizeService.findUnionId(vm.getUnionId());
                List<CouponQueryResp> couponQueryResps = orderService.solvedOrderRecord(orderlist);
                List<CouponQueryResp> resultCouponQueryResps = prizeConvertPrizeGood(couponQueryResps, prizeList,typeList);
                allList.addAll(resultCouponQueryResps);
                //查询所有优惠券
                List<OrderRecord> otherList1 =orderService.findNoWechatOrderByUserId(vm.getUnionId());
                List<CouponQueryResp> otherList = orderService.solvedOrderRecord(otherList1);
                List<Integer> typeList2 = new ArrayList<>();
                typeList2.add(3);
                typeList2.add(4);
                List<Prize> prizeList2=prizeService.findUnionId(vm.getUnionId());
                List<CouponQueryResp> couponQueryResps1 = prizeConvertPrizeGood(otherList, prizeList2,typeList2);
                allList.addAll(couponQueryResps1);
            }else if(vm.getType() ==2){
                //查询所有活动券
                List<OrderRecord> all =orderService.findOrderByUserId(vm.getUnionId());
                List<CouponQueryResp> list = orderService.solvedOrderRecord(all);
                typeList.add(1);
                List<Prize> prizeList2=prizeService.findUnionId(vm.getUnionId());
                List<CouponQueryResp> couponQueryResps1 = prizeConvertPrizeGood(list, prizeList2,typeList);
                allList.addAll(couponQueryResps1);
            }else{
                //查询所有组合卡券
                CouponReturnVm groupCoupon = prizeService.getCouponReturnVm(vm);
                map.put("groupCoupon",groupCoupon);
                //查询所有优惠券
                List<OrderRecord> otherList1 =orderService.findNoWechatOrderByUserId(vm.getUnionId());
                List<CouponQueryResp> otherList = orderService.solvedOrderRecord(otherList1);
                typeList.add(3);
                typeList.add(4);
                List<Prize> prizeList2=prizeService.findUnionId(vm.getUnionId());
                List<CouponQueryResp> couponQueryResps1 = prizeConvertPrizeGood(otherList, prizeList2,typeList);
                allList.addAll(couponQueryResps1);
            }
            map.put("allList",allList);
            result.setData(map);
            result.setState(0);
            result.setMessage("数据如上");
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    private List<CouponQueryResp> prizeConvertPrizeGood(List<CouponQueryResp> otherList, List<Prize> prizeList2,List<Integer> typeList) {
        if (prizeList2 != null && prizeList2.size() > 0) {
            List<Integer> goodIds = new ArrayList<>();
            for (Prize prize : prizeList2) {
                goodIds.add(prize.getGoodId());
            }
            List<PrizeGood> goodList = prizeGoodService.findByIds(goodIds,typeList);
            if (goodList != null && goodList.size() > 0) {
                CouponQueryResp entity = null;
                for (PrizeGood good : goodList) {
                    entity = new CouponQueryResp();
                    entity.setHeadImage(good.getGoodImg());
                    if (good.getPoint() != null) {
                        entity.setPoints(good.getPoint());
                    }
                    entity.setName(good.getGoodName());
                    entity.setUrl(good.getPagePath());
                    entity.setEndTime(good.getEndTime());
                    entity.setStartTime(DateUtil.format(good.getStartTime(), "yyyy-MM-DD hh:mm:ss"));
                    otherList.add(entity);
                }

            }
        }
        return otherList;
    }


    /**
     * 测试中奖概率
     * @param
     * @return
     */
    @PostMapping("test")
    public JsonResult Test(){
        JsonResult result = new JsonResult();
        String activityId ="smpBaileysFlActivity";
        List<PrizeGood> enableGoods = prizeGoodService.getEnableIdsAndStockIsNotNullByActivityId(activityId);
        if (enableGoods.size() == 0) {
            result.setState(-1);
            result.setMessage("很遗憾您未抽中，谢谢参与");
            return result;
        }
        Double maxNum = 0D;
        for (PrizeGood good : enableGoods) {
            maxNum = maxNum + good.getProbability();
        }
        if (maxNum == 0) {
            result.setState(-1);
            result.setMessage("概率出问题了");
            return result;
        }
        log.info("最大数:{}", maxNum);
        Integer point20Count =0;
        Integer point50Count =0;
        Integer point100Count =0;
        Integer entity700mlpointCount =0;
        Integer entity200mlpointCount =0;
        Integer nousepointCount =0;
        for(int i =0;i<=1000;i++){
            //获取0-总概率值得随机数
            double min = 0d;
            Double randomNum = min + new Random().nextDouble() * (maxNum - min);
            log.info("randomNum:{}", randomNum);
            Integer goodId =null;
            for (PrizeGood good : enableGoods) {
                randomNum = randomNum - good.getProbability();
                if (randomNum <= 0) {
                    goodId = good.getId();
                    if(goodId ==56){
                        point20Count +=1;
                        log.info("20积分中奖啦,当前累计中奖次数:{}", point20Count);
                    }else if(goodId ==57){
                        point50Count +=1;
                        log.info("50积分中奖啦,当前累计中奖次数:{}", point50Count);
                    }else if(goodId ==58){
                        point100Count +=1;
                        log.info("100积分中奖啦,当前累计中奖次数:{}", point100Count);
                    }else if(goodId ==54){
                        entity200mlpointCount +=1;
                        log.info("Baileys 百利甜酒原味200ml中奖啦,当前累计中奖次数:{}", entity200mlpointCount);
                    }else if(goodId ==55){
                        entity700mlpointCount +=1;
                        log.info("Baileys 百利甜酒原味700ml中奖啦,当前累计中奖次数:{}", entity700mlpointCount);
                    }else{
                        nousepointCount+=1;
                        log.info("无效商品中奖次数:{}", nousepointCount);
                    }
                    break;
                }
            }
        }
        Map<String,Integer> map =new HashMap<>();
        map.put("20积分中奖次数",point20Count);
        map.put("50积分中奖次数",point50Count);
        map.put("100积分中奖次数",point100Count);
        map.put("Baileys 百利甜酒原味200ml中奖次数",entity200mlpointCount);
        map.put("Baileys 百利甜酒原味700ml中奖次数",entity700mlpointCount);
        map.put("无效商品中奖次数",nousepointCount);
        result.setData(map);
        return  result;
    }

    /**
     *
     *同步ERP物流信息
     */
    //@Scheduled(cron = "0 0 3 * * ?")
    public void LogisticsSyncQuery(){
        prizeGoodService.LogisticsSyncQuery();
    }

    /**
     * 查询是否显示发起助力活动，卡券核销状态，二维码场景，核销时间
     * @param
     * @return
     */
    @PostMapping("queryHxLaunchHelp")
    public JsonResult queryHxLaunchHelp(@RequestBody LaunchHelpVM vm) {
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(vm.getUnionId())) {
            result.setState(-1);
            result.setMessage("unionId为空");
            return result;
        }
        if (vm.getPrizeId() == null) {
            result.setState(-1);
            result.setMessage("prizeId为空");
            return result;
        }
        if (vm.getGoodId() == null) {
            result.setState(-1);
            result.setMessage("goodId为空");
            return result;
        }
        if (vm.getMdmHelpActivityId() == null) {
            result.setState(-1);
            result.setMessage("mdmHelpActivityId为空");
            return result;
        }
        try {
            result = prizeService.queryHxLaunchHelp(vm);
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 查询活动下奖品总概率
     * @param
     * @return
     */
    @PostMapping("queryActivityProbability")
    public JsonResult queryActivityProbability (@RequestBody ActivityProbabilityVM vm) {
        JsonResult result = new JsonResult();
        log.info("queryActivityProbability req:" + JSON.toJSONString(vm));
        if (vm.getProbability() == null) {
            result.setState(-1);
            result.setMessage("probability为空");
            return result;
        }
        if (vm.getActivityId() == null) {
            result.setState(-1);
            result.setMessage("activityId为空");
            return result;
        }
        result = prizeGoodService.queryActivityProbability(vm);
        return result;

    }

}
